package self.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import self.mapper.UserMapper;
import self.pojo.Menu;
import self.pojo.Role;
import self.pojo.User;
import self.security.entity.SecurityUser;

import java.util.List;

/**
 * 作者: liYU
 * 项目名称: WX_Self_Iot_parent
 * 标题: MyUserDetailService
 * 该类描述: TODO
 * 创建日期: 2025/4/29 19:22
 */
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //这里传递的是用户名，先判断用户名是否为空
        if (StrUtil.isEmpty(username)) {
            throw new UsernameNotFoundException("用户名有误");
        }
        //根据用户名查询用户对象
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        User user = userMapper.selectOne(userQueryWrapper);
        if (user == null) {
            throw new UsernameNotFoundException("用户名有误");
        }
        //根据用户ID查询所有的权限
        List<Role> roles = userMapper.findRolesById(user.getId());
        //根据用户ID查询所有的菜单
        List<Menu> menus = userMapper.finMenusById(user.getId());
        //将role和menu封装成List<String结构>
        SecurityUser securityUser = wrapSecurityUser(roles, menus, user);
        return securityUser;
     }
}
